﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using gt.dotnetcore.webapi.Model;

namespace gt.dotnetcore.webapi.DataAccess.Impl
{
    public class MemoryBookDAL : IBookDAL
    {
        private static Dictionary<string, BookModel> _booContainer = new Dictionary<string, BookModel>();

        public MemoryBookDAL()
        {
            _booContainer.Clear();

            #region TestData

            _booContainer.Add("西游记", new BookModel { Name = "西游记", Author = "吴承恩", Introduction = "四大名著之一", MacketTime = DateTime.Parse("2019-04-20"), Price = 64.6M });
            _booContainer.Add("水浒传", new BookModel { Name = "水浒传", Author = "施耐庵", Introduction = "四大名著之二", MacketTime = DateTime.Parse("2019-07-05"), Price = 45.7M });
            _booContainer.Add("红楼梦", new BookModel { Name = "红楼梦", Author = "曹雪芹", Introduction = "四大名著之三", MacketTime = DateTime.Parse("2019-02-18"), Price = 88.0M });
            _booContainer.Add("三国演义", new BookModel { Name = "三国演义", Author = "罗贯中", Introduction = "四大名著之四", MacketTime = DateTime.Parse("2019-10-01"), Price = 74.8M });

            #endregion
        }

        public void AddBook(BookModel model)
        {
            if (_booContainer.ContainsKey(model.Name))
                _booContainer[model.Name] = model;
            else
                _booContainer.Add(model.Name, model);
        }

        public List<BookModel> GetAllBooks()
        {
            if (_booContainer.Count == 0) return null;
            return _booContainer.Values.ToList();
        }

        public BookModel GetBook(string name)
        {
            _booContainer.TryGetValue(name, out BookModel book);
            return book;
        }

        public List<BookModel> GetBooks(string author)
        {
            var allBooks = GetAllBooks();
            return allBooks.FindAll(x => string.Equals(x.Author, author, StringComparison.CurrentCultureIgnoreCase));
        }
    }
}
